"""
GT-LMS Command Line Interface Implementation
This module provides the CLI interface for interacting with the LMS system
"""

import getpass
import sys
import os
from typing import Optional

# Add project root directory to Python path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

# Import system components
from system.lms_system import LMSSystem
from models.user import User, Student, Teacher, Admin

# Import utility classes
from utils.exceptions import AuthenticationException, LMSException


class CLI:
    """
    GT-LMS Command Line Interface Class
    This class provides the main user interface for the system
    """

    def __init__(self, system: LMSSystem):
        """
        Initialize CLI with LMS system

        Parameters:
            system (LMSSystem): LMS system instance
        """
        self.system = system
        self.current_user: Optional[User] = None
        self.is_running = False

    def color_print(self, text: str, color: str = "white") -> None:
        """
        Print colored text (if terminal supports it)

        Parameters:
            text (str): Text to print
            color (str): Color name
        """
        colors = {
            "red": "\033[91m",
            "green": "\033[92m",
            "yellow": "\033[93m",
            "blue": "\033[94m",
            "magenta": "\033[95m",
            "cyan": "\033[96m",
            "white": "\033[97m",
            "bold": "\033[1m",
            "underline": "\033[4m",
            "end": "\033[0m"
        }

        # Check if terminal supports color
        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
            color_code = colors.get(color, colors["white"])
            print(f"{color_code}{text}{colors['end']}")
        else:
            print(text)

    def start(self) -> None:
        """
        Start CLI interface
        """
        self.is_running = True
        self.color_print("=" * 50, "cyan")
        self.color_print("Welcome to GT-LMS Learning Management System", "cyan")
        self.color_print("=" * 50, "cyan")

        while self.is_running:
            if self.current_user is None:
                self.login_interface()
            else:
                self.display_main_menu()

    def login_interface(self) -> None:
        """
        Display login interface
        """
        print()
        self.color_print("--- Login ---", "cyan")
        print("1. Login")
        print("2. Register")
        print("3. Exit")

        try:
            choice = input("Please enter your choice: ").strip()
        except EOFError:
            print("Input error: Unable to read choice")
            return

        if choice == "1":
            self.handle_login()
        elif choice == "2":
            self.handle_register()
        elif choice == "3":
            self.is_running = False
            self.color_print("Thank you for using GT-LMS!", "green")
        else:
            self.color_print("Invalid choice, please try again", "red")

    def handle_login(self) -> None:
        """
        Handle user login
        """
        try:
            email = input("Email: ").strip()
            password = getpass.getpass("Password: ")

            # Authenticate user using authentication system
            if self.system.auth_system:
                if self.system.auth_system.login(email, password):
                    # Get current logged in user object
                    self.current_user = self.system.auth_system.current_user
                    self.color_print(f"Login successful! Welcome, {self.current_user.get_name()}", "green")
                else:
                    self.color_print("Login failed: Email or password incorrect", "red")
            else:
                # If authentication system is unavailable, use simulated login
                self.color_print(f"Login successful! Welcome, {email}", "green")
                self.current_user = email  # Placeholder

        except AuthenticationException as e:
            self.color_print(f"Login failed: {e.message}", "red")
        except Exception as e:
            self.color_print(f"Error occurred during login: {e}", "red")

    def display_main_menu(self) -> None:
        """
        Display main menu based on user role
        """
        if self.current_user is None:
            return

        print()
        self.color_print("=" * 40, "cyan")
        self.color_print(f"Main Menu - {self.current_user.get_name()}", "cyan")
        self.color_print("=" * 40, "cyan")

        # Display different menus based on user role
        user_type = type(self.current_user).__name__
        if user_type == "Admin":
            self.display_admin_menu()
        elif user_type == "Teacher":
            self.display_teacher_menu()
        elif user_type == "Student":
            self.display_student_menu()
        else:
            # Default general menu
            print("1. View Courses")
            print("2. View Assignments")
            print("3. View Grades")
            print("4. System Backup")
            print("5. View System Statistics")
            print("6. Logout")
            print("7. Exit")

            choice = input("Please enter your choice: ").strip()
            self.handle_default_input(choice)

    def handle_default_input(self, choice: str) -> None:
        """
        Handle default menu input
        """
        if choice == "1":
            self.display_courses()
        elif choice == "2":
            self.display_assignments()
        elif choice == "3":
            self.display_grades()
        elif choice == "4":
            self.backup_system()
        elif choice == "5":
            self.display_system_statistics()
        elif choice == "6":
            self.logout()
        elif choice == "7":
            self.is_running = False
            self.color_print("Thank you for using GT-LMS!", "green")
        else:
            self.color_print("Invalid choice, please try again", "red")

    def display_student_menu(self) -> None:
        """
        Display student-specific menu
        """
        print()
        self.color_print("--- Student Menu ---", "blue")
        print("1. Enroll in Course")
        print("2. Drop Course")
        print("3. Submit Assignment")
        print("4. View Grades")
        print("5. View Progress")
        print("6. View Course List")
        print("7. Logout")
        print("8. Exit")

        choice = input("Please enter your choice: ").strip()
        self.handle_student_input(choice)

    def display_teacher_menu(self) -> None:
        """
        Display teacher-specific menu
        """
        print()
        self.color_print("--- Teacher Menu ---", "yellow")
        print("1. Create Course")
        print("2. Manage Courses")
        print("3. Create Assignment")
        print("4. Grade Assignment")
        print("5. View Class List")
        print("6. View Course Statistics")
        print("7. Logout")
        print("8. Exit")

        choice = input("Please enter your choice: ").strip()
        self.handle_teacher_input(choice)

    def display_admin_menu(self) -> None:
        """
        Display admin-specific menu
        """
        print()
        self.color_print("--- Admin Menu ---", "magenta")
        print("1. User Management")
        print("2. Course Management")
        print("3. System Statistics")
        print("4. Generate Reports")
        print("5. System Backup")
        print("6. System Restore")
        print("7. System Settings")
        print("8. Logout")
        print("9. Exit")

        choice = input("Please enter your choice: ").strip()
        self.handle_admin_input(choice)

    def handle_student_input(self, choice: str) -> None:
        """
        Handle student menu input
        """
        if choice == "1":
            self.handle_enroll_course(self.current_user)
        elif choice == "2":
            self.drop_course()
        elif choice == "3":
            self.submit_assignment()
        elif choice == "4":
            self.display_grades()
        elif choice == "5":
            self.view_progress()
        elif choice == "6":
            self.display_student_courses(self.current_user.get_id())
        elif choice == "7":
            self.logout()
        elif choice == "8":
            self.is_running = False
            self.color_print("Thank you for using GT-LMS!", "green")
        else:
            self.color_print("Invalid choice, please try again", "red")

    def handle_teacher_input(self, choice: str) -> None:
        """
        Handle teacher menu input
        """
        if choice == "1":
            self.handle_create_course(self.current_user)
        elif choice == "2":
            self.handle_manage_courses(self.current_user)
        elif choice == "3":
            self.create_assignment()
        elif choice == "4":
            self.grade_assignment()
        elif choice == "5":
            self.view_class_list()
        elif choice == "6":
            self.view_course_statistics()
        elif choice == "7":
            self.logout()
        elif choice == "8":
            self.is_running = False
            print("Thank you for using GT-LMS!")
        else:
            print("Invalid choice, please try again")

    def handle_admin_input(self, choice: str) -> None:
        """
        Handle admin menu input
        """
        if choice == "1":
            self.manage_users()
        elif choice == "2":
            self.manage_courses()
        elif choice == "3":
            self.display_system_statistics()
        elif choice == "4":
            self.generate_reports()
        elif choice == "5":
            self.backup_system()
        elif choice == "6":
            self.restore_system()
        elif choice == "7":
            self.system_settings()
        elif choice == "8":
            self.logout()
        elif choice == "9":
            self.is_running = False
            print("Thank you for using GT-LMS!")
        else:
            print("Invalid choice, please try again")

    def display_courses(self) -> None:
        """
        Display course list
        """
        print()
        self.color_print("--- Course List ---", "cyan")

        if not self.system or not self.system.course_manager:
            self.color_print("Course manager unavailable", "red")
            return

        courses = self.system.course_manager.get_all_courses()
        if not courses:
            self.color_print("No courses available", "yellow")
            return

        # Display course information using table
        headers = ["ID", "Name", "Code", "Teacher", "Description", "Capacity", "Current Students"]
        rows = []

        for course in courses:
            teacher = None
            if self.system.user_manager:
                teacher = self.system.user_manager.get_user(course.get_teacher_id())

            teacher_name = teacher.get_name() if teacher else "Unknown Teacher"

            rows.append([
                course.get_id(),
                course.get_name(),
                course.get_id(),
                teacher_name,
                course.get_description()[:30] + "..." if len(course.get_description()) > 30 else course.get_description(),
                str(course.get_max_students()),
                str(course.get_current_students())
            ])

        self.display_table(headers, rows)

    def display_student_courses(self, student_id: str) -> None:
        """
        Display student course enrollment list

        Parameters:
            student_id (str): Student ID
        """
        print()
        self.color_print(f"--- {self.current_user.get_name()}'s Courses ---", "cyan")

        if not self.system or not self.system.enrollment_manager:
            self.color_print("Enrollment manager unavailable", "red")
            return

        # Get student enrollment records
        student_enrollments = self.system.enrollment_manager.get_student_enrollments(student_id)
        if not student_enrollments:
            self.color_print("No enrollments", "yellow")
            return

        # Display course information using table
        headers = ["ID", "Name", "Code", "Teacher", "Description", "Capacity", "Current Students"]
        rows = []

        for enrollment in student_enrollments:
            if enrollment.status != "active":  # Only show active enrollments
                continue
                
            course_id = enrollment.course_id
            course = self.system.course_manager.get_course(course_id)
            
            if not course:
                continue
                
            teacher = None
            if self.system.user_manager:
                teacher = self.system.user_manager.get_user(course.get_teacher_id())

            teacher_name = teacher.get_name() if teacher else "Unknown Teacher"

            rows.append([
                course.get_id(),
                course.get_name(),
                course.get_id(),
                teacher_name,
                course.get_description()[:30] + "..." if len(course.get_description()) > 30 else course.get_description(),
                str(course.get_max_students()),
                str(course.get_current_students())
            ])

        if not rows:
            self.color_print("No active enrollments", "yellow")
        else:
            self.display_table(headers, rows)

    def display_help(self) -> None:
        """
        Display help information
        """
        print()
        self.color_print("=" * 50, "cyan")
        self.color_print("GT-LMS Learning Management System - Help Information", "cyan")
        self.color_print("=" * 50, "cyan")

        help_text = """
System Roles:
  - Student: Can enroll/drop courses, submit assignments, view grades and progress
  - Teacher: Can create/manage courses, create assignments, grade assignments, view class lists
  - Admin: Can manage users, courses, view system statistics and generate reports

Common Features:
  - Course Enrollment: Students can select courses of interest for learning
  - Assignments: Teachers can create assignments, students can submit assignments
  - Grades: Teachers can grade assignments and enter scores
  - Progress: Students can view their learning progress

Notes:
  - Please keep your account information safe
  - Contact system administrator if you encounter problems
  - System will automatically save your data
        """

        print(help_text)

    def display_assignments(self) -> None:
        """
        Display assignments
        """
        print("\n--- Assignments ---")
        # This will display actual assignments in the system
        print("Assignment list functionality will be implemented here")

    def display_system_statistics(self) -> None:
        """
        Display system statistics
        """
        print()
        self.color_print("--- System Statistics ---", "cyan")

        if self.system and self.system.is_system_ready():
            stats = self.system.get_statistics()

            # Display statistics information
            for key, value in stats.items():
                if key == "start_time":
                    print(f"System Start Time: {value}")
                elif key == "uptime":
                    print(f"Uptime: {value}")
                elif key == "users_count":
                    print(f"Total Users: {value}")
                elif key == "courses_count":
                    print(f"Total Courses: {value}")
                elif key == "enrollments_count":
                    print(f"Enrollment Records: {value}")
        else:
            self.color_print("Unable to get system statistics", "red")

    def backup_system(self) -> None:
        """
        Backup system data
        """
        print("\n--- System Backup ---")
        if self.system:
            if self.system.backup_system():
                print("System backup completed")
            else:
                print("System backup failed")
        else:
            print("System unavailable, cannot backup")

    def logout(self) -> None:
        """
        Handle user logout
        """
        if self.system.auth_system:
            self.system.auth_system.logout()
        self.current_user = None
        print("You have successfully logged out")

    # Student feature methods
    def handle_enroll_course(self, student: Student) -> None:
        """
        Handle student course enrollment
        """
        print("\n--- Course Enrollment ---")
        
        # Display available courses
        courses = self.system.course_manager.get_all_courses()
        if not courses:
            print("No courses available")
            return
        
        print("Available Courses:")
        for i, course in enumerate(courses, 1):
            teacher = self.system.user_manager.get_user(course.get_teacher_id())
            teacher_name = teacher.get_name() if teacher else "Unknown Teacher"
            print(f"{i}. {course.get_name()} ({course.get_id()}) - Teacher: {teacher_name}")
            print(f"   Description: {course.get_description()}")
            print(f"   Status: {course.get_current_students()}/{course.get_max_students()} students")
            print()
        
        try:
            choice = input("Please select course number to join (or enter 0 to return): ").strip()
            if choice == '0':
                return
            
            course_index = int(choice) - 1
            if 0 <= course_index < len(courses):
                course = courses[course_index]
                
                # Check if student already enrolled in this course
                if self.system.enrollment_manager.is_student_enrolled(student.get_id(), course.get_id()):
                    print("You have already selected this course")
                    return
                
                # Check if course is full
                if course.get_current_students() >= course.get_max_students():
                    print("This course is full, cannot select")
                    return
                
                # Use EnrollmentManager for course enrollment
                enrollment = self.system.enrollment_manager.create_enrollment(
                    student_id=student.get_id(),
                    course_id=course.get_id()
                )
                
                if enrollment:
                    print(f"Successfully enrolled in course: {course.get_name()}")
                else:
                    print("Enrollment failed, please try again")
            else:
                print("Invalid course number")
                
        except ValueError:
            print("Please enter a valid number")
        except Exception as e:
            print(f"Error during enrollment: {e}")

    def drop_course(self) -> None:
        """Drop course function"""
        print("\n--- Drop Course ---")
        course_id = input("Please enter the course ID to drop: ").strip()
        if self.system.course_manager.drop_student(self.current_user.get_id(), course_id):
            print("Course dropped successfully!")
        else:
            print("Course drop failed, please check if the course ID is valid")

    def submit_assignment(self) -> None:
        """Submit assignment function"""
        print("\n--- Submit Assignment ---")
        assignment_id = input("Please enter assignment ID: ").strip()
        content = input("Please enter assignment content: ").strip()
        
        # Debug information
        print(f"[DEBUG] Current user ID: {self.current_user.get_id()}")
        print(f"[DEBUG] Assignment ID: {assignment_id}")
        print(f"[DEBUG] Original content: '{content}'")
        
        # Wrap content in dictionary format to meet Assignment validation requirements
        content_dict = {"text": content}
        print(f"[DEBUG] Wrapped content: {content_dict}")
        
        try:
            result = self.system.assignment_manager.submit_assignment(
                self.current_user.get_id(), assignment_id, content_dict
            )
            print(f"[DEBUG] Submission result: {result}")
            
            if result:
                print("Assignment submitted successfully!")
            else:
                print("Assignment submission failed")
                
                # Try to get more information
                assignment = self.system.assignment_manager.get_assignment(assignment_id)
                if assignment:
                    print(f"[DEBUG] Found assignment: {assignment.get_title()}")
                    print(f"[DEBUG] Assignment file requirement: {getattr(assignment, 'file_required', 'N/A')}")
                    try:
                        is_valid = assignment.validate_submission(content_dict)
                        print(f"[DEBUG] Content validation result: {is_valid}")
                    except Exception as e:
                        print(f"[DEBUG] Validation exception: {e}")
                else:
                    print("[DEBUG] Assignment not found")
                    
        except Exception as e:
            print(f"[DEBUG] Submission exception: {e}")
            print(f"[DEBUG] Exception type: {type(e)}")
            import traceback
            traceback.print_exc()
            print("Assignment submission failed")

    def view_progress(self) -> None:
        """View learning progress"""
        print("\n--- Learning Progress ---")
        progress = self.system.progress_tracker.get_student_progress(self.current_user.get_id())
        if progress:
            print(f"Total Credits: {progress.get('total_credits', 0)}")
            print(f"Average Grade: {progress.get('average_grade', 0):.2f}")
            print(f"Completed Courses: {progress.get('completed_courses', 0)}")
        else:
            print("No progress information available")

    def display_grades(self) -> None:
        """
        Display grades:
        - Student: View their own course grades
        - Teacher: View student grades in their courses
        - Other roles: Show function limitations
        """
        print("\n--- Grades ---")

        if not self.current_user:
            self.color_print("Please login first", "red")
            return

        # Student view their own grades
        if isinstance(self.current_user, Student):
            grades = self.current_user.get_grades()
            if not grades:
                self.color_print("No grade records available", "yellow")
                return

            headers = ["Course ID", "Course Name", "Grade"]
            rows = []
            for course_id, grade in grades.items():
                course_name = "Unknown Course"
                if self.system and getattr(self.system, 'course_manager', None):
                    course = self.system.course_manager.get_course(course_id)
                    if course:
                        course_name = course.get_name()
                rows.append([course_id, course_name, str(grade)])

            self.display_table(headers, rows)
            return

        # Teacher view student grades in their courses
        if isinstance(self.current_user, Teacher):
            # Try to get teacher's course list
            teaching_courses = []
            if hasattr(self.current_user, 'get_teaching_courses'):
                teaching_courses = self.current_user.get_teaching_courses()
            elif self.system and getattr(self.system, 'course_manager', None):
                try:
                    teaching_courses = self.system.course_manager.get_teacher_courses(self.current_user.get_id())
                except Exception:
                    teaching_courses = []

            if not teaching_courses:
                self.color_print("You currently don't teach any courses", "yellow")
                return

            headers = ["Course ID", "Course Name", "Student", "Grade"]
            rows = []

        # Iterate through all students in the system, collect their grades in teacher's courses (try to use user_manager)
            if self.system and getattr(self.system, 'user_manager', None):
                all_users = self.system.user_manager.get_all_users()
                for u in all_users:
                    # Only process student objects
                    if not hasattr(u, 'get_grades'):
                        continue
                    sgrades = u.get_grades() or {}
                    for cid, grade in sgrades.items():
                        if cid in teaching_courses:
                            course_name = cid
                            if self.system and getattr(self.system, 'course_manager', None):
                                course = self.system.course_manager.get_course(cid)
                                if course:
                                    course_name = course.get_name()
                            rows.append([cid, course_name, u.get_name(), str(grade)])

            if not rows:
                self.color_print("No related grade records available", "yellow")
                return

            self.display_table(headers, rows)
            return

        # Other roles (e.g. Admin) only show a prompt for now
        self.color_print("Only students and teachers can view grades; administrators please use statistics/report features.", "yellow")

    # Teacher feature methods
    def handle_create_course(self, teacher: Teacher) -> None:
        """
        Handle teacher course creation
        """
        print("\n--- Create Course ---")
        
        try:
            name = input("Course Name: ").strip()
            if not name:
                print("Course name cannot be empty")
                return
            
            # Course code removed, using course ID as unique identifier
            
            description = input("Course Description: ").strip()
            if not description:
                print("Course description cannot be empty")
                return
            
            try:
                max_students = int(input("Maximum Students (default 50): ").strip() or "50")
                if max_students <= 0:
                    print("Maximum students must be greater than 0")
                    return
            except ValueError:
                print("Please enter a valid number")
                return
            
            # Create course
            course = self.system.course_manager.create_course(
                name=name,
                description=description,
                teacher_id=teacher.get_id(),
                max_students=max_students
            )
            
            if course:
                print(f"Successfully created course: {name} — ID: {course.get_id()}")
            else:
                print("Course creation failed")
                
        except KeyboardInterrupt:
            print("\nOperation cancelled")
        except Exception as e:
            print(f"Error creating course: {e}")

    def handle_manage_courses(self, teacher: Teacher) -> None:
        """
        Handle teacher course management
        """
        print("\n--- Manage Courses ---")
        
        # Get teacher's course list
        courses = self.system.course_manager.get_teacher_courses(teacher.get_id())
        if not courses:
            print("You haven't created any courses yet")
            return
        
        print("Your Courses:")
        for i, course in enumerate(courses, 1):
            print(f"{i}. {course.get_name()} ({course.get_id()})")
            print(f"   Description: {course.get_description()}")
            print(f"   Students: {course.get_current_students()}/{course.get_max_students()}")
            print()
        
        try:
            choice = input("Please select course number to manage (or enter 0 to return): ").strip()
            if choice == '0':
                return
            
            course_index = int(choice) - 1
            if 0 <= course_index < len(courses):
                course = courses[course_index]
                self.handle_manage_single_course(course)
            else:
                print("Invalid course number")
                
        except ValueError:
            print("Please enter a valid number")
        except Exception as e:
            print(f"Error managing courses: {e}")
    
    def handle_manage_single_course(self, course) -> None:
        """
        Manage single course
        """
        while True:
            print(f"\n--- Manage Course: {course.get_name()} ---")
            print("1. View Course Details")
            print("2. View Enrolled Students")
            print("3. Update Course Information")
            print("4. Delete Course")
            print("0. Return")
            
            choice = input("Select operation: ").strip()
            
            if choice == '1':
                self.display_course_details(course)
            elif choice == '2':
                self.display_course_students(course)
            elif choice == '3':
                self.update_course_info(course)
            elif choice == '4':
                if self.delete_course(course):
                    break
            elif choice == '0':
                break
            else:
                print("Invalid choice")
    
    def display_course_details(self, course) -> None:
        """
        Display course details
        """
        print(f"\n--- Course Details ---")
        print(f"Course Name: {course.get_name()}")
        print(f"Course ID: {course.get_id()}")
        print(f"Course Description: {course.get_description()}")
        print(f"Maximum Students: {course.get_max_students()}")
        print(f"Current Students: {course.get_current_students()}")
        print(f"Created At: {course.get_created_at()}")
        
        teacher = self.system.user_manager.get_user(course.get_teacher_id())
        teacher_name = teacher.get_name() if teacher else "Unknown Teacher"
        print(f"Teacher: {teacher_name}")
    
    def display_course_students(self, course) -> None:
        """
        Display course student list
        """
        print(f"\n--- Enrolled Students List ---")
        student_ids = course.get_student_ids()
        
        if not student_ids:
            print("No students enrolled in this course")
            return
        
        print(f"Total {len(student_ids)} students:")
        for i, student_id in enumerate(student_ids, 1):
            student = self.system.user_manager.get_user(student_id)
            if student:
                print(f"{i}. {student.get_name()} ({student.get_email()})")
            else:
                print(f"{i}. Unknown Student (ID: {student_id})")
    
    def update_course_info(self, course) -> None:
        """
        Update course information
        """
        print(f"\n--- Update Course Information ---")
        print("Current Information:")
        print(f"Name: {course.get_name()}")
        print(f"Course ID: {course.get_id()}")
        print(f"Description: {course.get_description()}")
        print(f"Maximum Students: {course.get_max_students()}")
        
        new_name = input(f"New Name (leave empty to keep original): ").strip()
        new_description = input(f"New Description (leave empty to keep original): ").strip()
        
        try:
            new_max_students_input = input(f"New Maximum Students (leave empty to keep original): ").strip()
            new_max_students = int(new_max_students_input) if new_max_students_input else course.get_max_students()
            
            if new_max_students <= 0:
                print("Maximum students must be greater than 0")
                return
                
            # Update course information
            if new_name:
                course.name = new_name
            if new_description:
                course.description = new_description
            course.max_students = new_max_students
            
            print("Course information updated successfully!")
            
        except ValueError:
            print("Please enter a valid number")
        except Exception as e:
            print(f"Error updating course information: {e}")
    
    def delete_course(self, course) -> bool:
        """
        Delete course
        """
        print(f"\n--- Delete Course ---")
        print(f"Are you sure you want to delete course '{course.get_name()}'?")
        print("Warning: This operation will delete all related enrollment records and assignment data!")
        
        confirm = input("Enter 'yes' to confirm deletion: ").strip().lower()
        if confirm != 'yes':
            print("Deletion operation cancelled")
            return False
        
        try:
            # Delete course from all related data structures
            course_id = course.get_id()
            teacher_id = course.get_teacher_id()
            
            # Remove from course dictionary
            if course_id in self.system.course_manager.courses:
                del self.system.course_manager.courses[course_id]
            
            # Remove from teacher's course list
            if teacher_id in self.system.course_manager.teacher_courses:
                if course_id in self.system.course_manager.teacher_courses[teacher_id]:
                    self.system.course_manager.teacher_courses[teacher_id].remove(course_id)
            
            # Remove from student enrollment lists
            for student_id in course.get_student_ids():
                if student_id in self.system.course_manager.student_enrollments:
                    if course_id in self.system.course_manager.student_enrollments[student_id]:
                        self.system.course_manager.student_enrollments[student_id].remove(course_id)
            
            print(f"Course '{course.get_name()}' deleted successfully!")
            return True
            
        except Exception as e:
            print(f"Error deleting course: {e}")
            return False

    def create_assignment(self) -> None:
        """Create assignment"""
        print("\n--- Create Assignment ---")
        course_id = input("Course ID: ").strip()
        title = input("Assignment Title: ").strip()
        description = input("Assignment Description: ").strip()
        due_date = input("Due Date (YYYY-MM-DD): ").strip()
        
        # Validate maximum score input
        max_score_input = input("Maximum Score: ").strip()
        if not max_score_input:
            print("Error: Maximum score cannot be empty")
            return
            
        try:
            max_score = float(max_score_input)
            if max_score <= 0:
                print("Error: Maximum score must be greater than 0")
                return
        except ValueError:
            print("Error: Please enter a valid number as maximum score")
            return
        
        assignment = self.system.assignment_manager.create_assignment(
            course_id, title, description, due_date, max_score
        )
        if assignment:
            print(f"Assignment created successfully! Assignment ID: {assignment.get_id()}")
        else:
            print("Assignment creation failed")

    def grade_assignment(self) -> None:
        """Grade assignment"""
        print("\n--- Grade Assignment ---")
        assignment_id = input("Assignment ID: ").strip()
        submission_id = input("Submission ID: ").strip()
        
        # Validate score input
        score_input = input("Score: ").strip()
        if not score_input:
            print("Error: Score cannot be empty")
            return
            
        try:
            score = float(score_input)
            if score < 0 or score > 100:
                print("Error: Score must be between 0-100")
                return
        except ValueError:
            print("Error: Please enter a valid numeric score")
            return
            
        feedback = input("Feedback: ").strip()
        
        result = self.system.assignment_manager.grade_submission(submission_id, self.current_user.user_id, score, feedback)
        if result:
            print("Grading completed!")
        else:
            print("Grading failed")

    def view_class_list(self) -> None:
        """View class roster"""
        print("\n--- Class Roster ---")
        course_id = input("Course ID: ").strip()
        students = self.system.course_manager.get_course_students(course_id)
        if students:
            print(f"Student roster for course {course_id}:")
            for student in students:
                print(f"- {student.get_name()} ({student.get_email()})")
        else:
            print("No students enrolled in this course")

    def view_course_statistics(self) -> None:
        """View course statistics"""
        print("\n--- Course Statistics ---")
        course_id = input("Course ID: ").strip()
        stats = self.system.analytics.get_course_statistics(course_id)
        if stats:
            print(f"Course Statistics:")
            for key, value in stats.items():
                print(f"{key}: {value}")
        else:
            print("Unable to retrieve course statistics")

    def manage_specific_course(self, course_id: str) -> None:
        """Manage specific course"""
        print(f"\n--- Manage Course {course_id} ---")
        print("1. View Class Roster")
        print("2. Create Assignment")
        print("3. View Assignment Submissions")
        print("4. Return")
        
        choice = input("Please select operation: ").strip()
        if choice == "1":
            self.view_class_list()
        elif choice == "2":
            self.create_assignment()
        elif choice == "3":
            self.view_assignment_submissions(course_id)
        elif choice == "4":
            return

    def view_assignment_submissions(self, course_id: str) -> None:
        """View assignment submissions"""
        print("\n--- Assignment Submissions ---")
        assignments = self.system.assignment_manager.get_course_assignments(course_id)
        if not assignments:
            print("No assignments for this course")
            return
            
        print("Assignment List:")
        for assignment in assignments:
            print(f"ID: {assignment.get_id()}, Title: {assignment.get_title()}")
        
        assignment_id = input("Please enter assignment ID to view submissions: ").strip()
        submissions = self.system.assignment_manager.get_assignment_submissions(assignment_id)
        
        if submissions:
            print(f"Submissions for assignment {assignment_id}:")
            for submission in submissions:
                student = self.system.user_manager.get_user_by_id(submission.get_student_id())
                print(f"- {student.get_name()}: {submission.get_score() or 'Not graded'}")
        else:
            print("No submissions")

    # Admin feature methods
    def manage_users(self) -> None:
        """User Management"""
        print("\n--- User Management ---")
        print("1. View All Users")
        print("2. Create User")
        print("3. Edit User")
        print("4. Delete User")
        print("5. Reset User Password")
        print("6. Return")
        
        choice = input("Please select operation: ").strip()
        if choice == "1":
            self.list_all_users()
        elif choice == "2":
            self.create_user()
        elif choice == "3":
            self.edit_user()
        elif choice == "4":
            self.delete_user()
        elif choice == "5":
            self.reset_user_password()
        elif choice == "6":
            return

    def list_all_users(self) -> None:
        """List all users"""
        print("\n--- All Users ---")
        users = self.system.user_manager.get_all_users()
        
        if not users:
            print("No users")
            return
            
        # Get terminal width
        try:
            import os
            terminal_width = os.get_terminal_size().columns
        except:
            # Use default value if terminal width cannot be obtained
            terminal_width = 80
        
        # Use minimal format if terminal width is too narrow
        if terminal_width < 70:
            print("\n--- User List (Minimal Format) ---")
            print("-" * terminal_width)
            
            for user in users:
                # Only show first 4 characters of ID and name
                id_short = user.user_id[:4] if len(user.user_id) > 4 else user.user_id
                name_short = user.get_name()[:4] if len(user.get_name()) > 4 else user.get_name()
                # Get role initial
                role_short = user.get_role()[0] if user.get_role() else ""
                
                # Ensure each line doesn't exceed terminal width
                line = f"{id_short} {name_short} ({role_short})"
                if len(line) > terminal_width - 2:
                    line = line[:terminal_width-2]
                
                print(line)
            
            print("-" * terminal_width)
        else:
            # Display user information in table format
            headers = ["ID", "Name", "Email", "Role"]
            rows = []
            
            for user in users:
                rows.append([
                    user.user_id,
                    user.get_name(),
                    user.email,
                    user.get_role()
                ])
            
            # Use larger column width to display user information, especially name column
            self.display_table(headers, rows, max_col_width=25)
            
        # Display total user count
        print(f"\nTotal Users: {len(users)}")

    def create_user(self) -> None:
        """Create user"""
        print("\n--- Create User ---")
        name = input("Name: ").strip()
        email = input("Email: ").strip()
        password = input("Password: ").strip()
        role = input("Role (student/teacher/admin): ").strip().lower()
        
        # Prepare user data
        user_data = {
            'name': name,
            'email': email,
            'password': password
        }
        
        if role == "student":
            user_data['user_id'] = input("Student ID: ").strip()
            user_data['major'] = input("Major: ").strip()
            user_data['student_number'] = user_data['user_id']  # Use student ID as student number
        elif role == "teacher":
            user_data['user_id'] = input("Teacher ID: ").strip()
            user_data['department'] = input("Department: ").strip()
            user_data['employee_id'] = user_data['user_id']  # Use teacher ID as employee ID
        elif role == "admin":
            user_data['user_id'] = input("Admin ID: ").strip()
            permissions = input("Permissions (comma-separated): ").strip().split(",")
            user_data['admin_level'] = 1  # Default admin level
        else:
            print("Invalid role")
            return
        
        # Use generic create_user method
        user = self.system.user_manager.create_user(role, user_data)
            
        if user:
            print(f"User created successfully! User ID: {user.get_id()}")
        else:
            print("User creation failed")

    def edit_user(self) -> None:
        """Edit user"""
        print("\n--- Edit User ---")
        user_id = input("User ID: ").strip()
        user = self.system.user_manager.get_user_by_id(user_id)
        if not user:
            print("User does not exist")
            return
            
        print(f"Current Information - Name: {user.get_name()}, Email: {user.get_email()}")
        name = input("New Name (leave empty to skip): ").strip()
        email = input("New Email (leave empty to skip): ").strip()
        
        if name:
            user.set_name(name)
        if email:
            user.set_email(email)
            
        print("User information updated successfully!")

    def delete_user(self) -> None:
        """Delete user"""
        print("\n--- Delete User ---")
        user_id = input("User ID: ").strip()
        confirm = input(f"Are you sure you want to delete user {user_id}? (yes/no): ").strip().lower()
        
        if confirm == "yes":
            if self.system.user_manager.delete_user(user_id):
                print("User deleted successfully!")
            else:
                print("User deletion failed")
        else:
            print("Deletion operation cancelled")

    def reset_user_password(self) -> None:
        """Reset user password"""
        print("\n--- Reset User Password ---")
        user_id = input("User ID: ").strip()
        user = self.system.user_manager.get_user_by_id(user_id)
        if not user:
            print("User does not exist")
            return
            
        new_password = self.system.auth_system.reset_password(user.get_email())
        print(f"Password reset successful! New password: {new_password}")
        print("Please notify the user to change password promptly")

    def generate_reports(self) -> None:
        """Generate reports"""
        print("\n--- Generate Reports ---")
        print("1. User Statistics Report")
        print("2. Course Statistics Report")
        print("3. Grade Statistics Report")
        print("4. System Usage Report")
        
        choice = input("Please select report type: ").strip()
        
        try:
            choice_num = int(choice)
            if choice_num < 1 or choice_num > 4:
                print("Invalid selection")
                return
        except ValueError:
            print("Please enter a valid number")
            return
        
        # Get system statistics
        stats = self.system.get_statistics()
        
        # Generate different types of reports based on selection
        if choice_num == 1:
            # User Statistics Report
            report = f"""
User Statistics Report
====================
Total Users: {stats.get('users_count', 0)}
Admins: {len([u for u in self.system.user_manager.get_all_users() if u.get_role() == 'admin'])}
Teachers: {len([u for u in self.system.user_manager.get_all_users() if u.get_role() == 'teacher'])}
Students: {len([u for u in self.system.user_manager.get_all_users() if u.get_role() == 'student'])}
            """
        elif choice_num == 2:
            # Course Statistics Report
            report = f"""
Course Statistics Report
====================
Total Courses: {stats.get('courses_count', 0)}
Maximum Enrollment Capacity: {sum([course.get_max_students() for course in self.system.course_manager.get_all_courses()]) if self.system.course_manager else 0}
Average Enrollment: {stats.get('enrollments_count', 0) / max(stats.get('courses_count', 1), 1):.2f}
            """
        elif choice_num == 3:
            # Grade Statistics Report
            report = f"""
Grade Statistics Report
====================
Total Enrollments: {stats.get('enrollments_count', 0)}
Grade statistics feature under development...
            """
        else:
            # System usage report
            report = self.system.generate_report()
        
        # Display report
        print("\n" + "="*50)
        print(report)
        print("="*50)
        
        # Ask whether to save report
        save_choice = input("\nSave report to file? (y/n): ").strip().lower()
        if save_choice == 'y':
            filename = input("Please enter filename (default: report.txt): ").strip()
            if not filename:
                filename = "report.txt"
            
            try:
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(report)
                print(f"Report saved to: {filename}")
            except Exception as e:
                print(f"Error saving report: {e}")

    def restore_system(self) -> None:
        """System restore"""
        print("\n--- System Restore ---")
        backup_path = input("Backup file path: ").strip()
        confirm = input("Are you sure you want to restore the system? This will overwrite current data! (yes/no): ").strip().lower()
        
        if confirm == "yes":
            if self.system.restore_from_backup(backup_path):
                print("System restored successfully!")
            else:
                print("System restore failed")
        else:
            print("Restore operation cancelled")

    def system_settings(self) -> None:
        """System settings"""
        print("\n--- System Settings ---")
        print("1. Set session timeout")
        print("2. Set password policy")
        print("3. Set backup policy")
        print("4. View system configuration")
        
        choice = input("Please select setting: ").strip()
        if choice == "1":
            timeout = int(input("Session timeout (seconds): ").strip())
            self.system.auth_system.session_timeout = timeout
            print("Session timeout set successfully!")
        elif choice == "2":
            print("Password policy setting feature under development...")
        elif choice == "3":
            print("Backup policy setting feature under development...")
        elif choice == "4":
            config = self.system.get_configuration()
            print("Current system configuration:")
            for key, value in config.items():
                print(f"{key}: {value}")

    def handle_register(self) -> None:
        """
        Handle user registration
        """
        try:
            print("\n--- User Registration ---")
            
            # Get user information
            try:
                user_id = input("User ID: ").strip()
                if not user_id:
                    print("User ID cannot be empty")
                    return
            except EOFError:
                print("Input error: Unable to read user ID")
                return
            
            try:
                name = input("Name: ").strip()
                if not name:
                    print("Name cannot be empty")
                    return
            except EOFError:
                print("Input error: Unable to read name")
                return
                
            try:
                email = input("Email: ").strip()
                if not email:
                    print("Email cannot be empty")
                    return
            except EOFError:
                print("Input error: Unable to read email")
                return
            
            # Use regular input() instead of getpass() in non-interactive environments
            try:
                # Try to get password using getpass
                password = getpass.getpass("Password: ")
                confirm_password = getpass.getpass("Confirm Password: ")
            except Exception as e:
                # Fall back to regular input() if getpass is not available
                print(f"Note: Using plain text password input ({e})")
                try:
                    password = input("Password: ").strip()
                    confirm_password = input("Confirm Password: ").strip()
                except EOFError:
                    print("Input error: Unable to read password")
                    return
            
            # Verify password match
            if password != confirm_password:
                print("Error: Passwords do not match")
                return
            
            # Select user type
            print("\nSelect user type:")
            print("1. Student")
            print("2. Teacher") 
            print("3. Admin")
            
            try:
                user_type_choice = input("Please enter choice (1-3): ").strip()
            except EOFError:
                print("Input error: Unable to read user type selection")
                return
            
            if user_type_choice == "1":
                user_type = "student"
                try:
                    student_number = input("Student ID: ").strip()
                    major = input("Major: ").strip()
                    enrollment_year = input("Enrollment Year: ").strip()
                except EOFError:
                    print("Input error: Unable to read student information")
                    return
                
                user_data = {
                    'user_id': user_id,
                    'name': name,
                    'email': email,
                    'password': password,
                    'student_number': student_number,
                    'major': major,
                    'enrollment_year': enrollment_year
                }
                
            elif user_type_choice == "2":
                user_type = "teacher"
                try:
                    employee_id = input("Employee ID: ").strip()
                    department = input("Department: ").strip()
                    office_hours = input("Office Hours: ").strip()
                except EOFError:
                    print("Input error: Unable to read teacher information")
                    return
                
                user_data = {
                    'user_id': user_id,
                    'name': name,
                    'email': email,
                    'password': password,
                    'employee_id': employee_id,
                    'department': department,
                    'office_hours': office_hours
                }
                
            elif user_type_choice == "3":
                user_type = "admin"
                try:
                    admin_level = input("Admin Level (1-5): ").strip()
                except EOFError:
                    print("Input error: Unable to read admin level")
                    return
                
                user_data = {
                    'user_id': user_id,
                    'name': name,
                    'email': email,
                    'password': password,
                    'admin_level': int(admin_level) if admin_level.isdigit() else 1
                }
                
            else:
                print("Invalid selection")
                return
            
            # Create user
            if self.system.user_manager:
                user = self.system.user_manager.create_user(user_type, user_data)
                if user:
                    print(f"Registration successful! Welcome {name}!")
                else:
                    print("Registration failed, please check input information")
            else:
                print("User manager unavailable")
                
        except Exception as e:
            print(f"Error during registration: {e}")
            import traceback
            traceback.print_exc()

    def manage_courses(self) -> None:
        """
        Admin course management interface
        """
        print()
        self.color_print("--- Course Management ---", "magenta")
        print("1. View All Courses")
        print("2. Create New Course")
        print("3. Edit Course")
        print("4. Delete Course")
        print("5. Return to Main Menu")

        choice = input("Please enter your choice: ").strip()
        
        if choice == "1":
            self.display_courses()
        elif choice == "2":
            self.create_course()
        elif choice == "3":
            self.edit_course()
        elif choice == "4":
            self.delete_course()
        elif choice == "5":
            return
        else:
            self.color_print("Invalid selection, please try again", "red")

    def create_course(self) -> None:
        """
        Create new course
        """
        print()
        self.color_print("--- Create New Course ---", "magenta")
        
        try:
            course_id = input("Course ID: ").strip()
            name = input("Course Name: ").strip()
            description = input("Course Description: ").strip()
            teacher_id = input("Teacher ID: ").strip()
            
            # Optional fields with default values
            max_students_input = input("Maximum Students (default 50): ").strip()
            max_students = int(max_students_input) if max_students_input else 50
            
            credits_input = input("Credits (default 2): ").strip()
            credits = int(credits_input) if credits_input else 2
            
            # Validate input
            if not all([course_id, name, description, teacher_id]):
                self.color_print("Please fill in all required fields (Course ID, Course Name, Course Description, Teacher ID)", "red")
                return
            
            # Create course
            if self.system.course_manager:
                course_data = {
                    'course_id': course_id,
                    'name': name,  # Use correct field name
                    'description': description,
                    'teacher_id': teacher_id,
                    'max_students': max_students,
                    'credits': credits
                    # Other fields like semester, class time, location will use defaults or auto-derived values
                }
                
                course = self.system.course_manager.create_course(course_data)
                if course:
                    # Display generated internal course_id for future ID-based queries
                    cid = course.get_id() if hasattr(course, 'get_id') else getattr(course, 'course_id', '')
                    self.color_print(f"Course {name} created successfully! ID: {cid}", "green")
                else:
                    self.color_print("Course creation failed, please check input information", "red")
            else:
                self.color_print("Course manager unavailable", "red")
                
        except ValueError:
            self.color_print("Maximum students and credits must be numbers", "red")
        except Exception as e:
            self.color_print(f"Error creating course: {e}", "red")

    def edit_course(self) -> None:
        """
        Edit course information
        """
        print()
        self.color_print("--- Edit Course ---", "magenta")
        
        course_id = input("Please enter course ID to edit: ").strip()
        
        if not course_id:
            self.color_print("Course ID cannot be empty", "red")
            return
        
        # Get course information
        if not self.system.course_manager:
            self.color_print("Course manager unavailable", "red")
            return
            
        course = self.system.course_manager.get_course(course_id)
        if not course:
            self.color_print(f"Course with ID {course_id} not found", "red")
            return
        
        # Display current course information
        print(f"\nCurrent course information:")
        print(f"Name: {course.get_name()}")
        print(f"Course ID: {course.get_id()}")
        print(f"Description: {course.get_description()}")
        print(f"Teacher ID: {course.get_teacher_id()}")
        print(f"Maximum Students: {course.get_max_students()}")
        print(f"Schedule: {course.get_schedule()}")
        print(f"Location: {course.get_location()}")
        print(f"Credits: {course.get_credits()}")
        
        print("\nPlease enter new information (leave blank to keep current):")
        
        try:
            name = input(f"Course Name [{course.get_name()}]: ").strip()
            course_id_input = input(f"Course ID [{course.get_id()}]: ").strip()
            description = input(f"Course Description [{course.get_description()}]: ").strip()
            teacher_id = input(f"Teacher ID [{course.get_teacher_id()}]: ").strip()
            max_students = input(f"Maximum Students [{course.get_max_students()}]: ").strip()
            schedule = input(f"Schedule [{course.get_schedule()}]: ").strip()
            location = input(f"Location [{course.get_location()}]: ").strip()
            credits = input(f"Credits [{course.get_credits()}]: ").strip()
            
            # Prepare update data
            update_data = {}
            
            if name:
                update_data['title'] = name
            if course_id_input:
                update_data['course_id'] = course_id_input
            if description:
                update_data['description'] = description
            if teacher_id:
                update_data['teacher_id'] = teacher_id
            if max_students:
                try:
                    update_data['max_students'] = int(max_students)
                except ValueError:
                    self.color_print("Maximum students must be a number", "red")
                    return
            if schedule:
                update_data['schedule'] = schedule
            if location:
                update_data['location'] = location
            if credits:
                try:
                    update_data['credits'] = int(credits)
                except ValueError:
                    self.color_print("Credits must be a number", "red")
                    return
            
            # Update course
            if update_data:
                success = self.system.course_manager.update_course(course_id, update_data)
                if success:
                    self.color_print("Course information updated successfully!", "green")
                else:
                    self.color_print("Course information update failed", "red")
            else:
                self.color_print("No information to update", "yellow")
                
        except Exception as e:
            self.color_print(f"Error editing course: {e}", "red")

    def delete_course(self) -> None:
        """
        Delete course
        """
        print()
        self.color_print("--- Delete Course ---", "magenta")
        
        course_id = input("Please enter course ID to delete: ").strip()
        
        if not course_id:
            self.color_print("Course ID cannot be empty", "red")
            return
        
        # Get course information
        if not self.system.course_manager:
            self.color_print("Course manager unavailable", "red")
            return
            
        course = self.system.course_manager.get_course(course_id)
        if not course:
            self.color_print(f"Course with ID {course_id} not found", "red")
            return
        
        # Display course information
        print(f"\nCourse information:")
        print(f"Name: {course.get_name()}")
        print(f"Course ID: {course.get_id()}")
        print(f"Teacher ID: {course.get_teacher_id()}")
        
        # Confirm deletion
        confirm = input(f"\nAre you sure you want to delete course {course.get_name()}? (y/n): ").strip().lower()
        
        if confirm == 'y':
            success = self.system.course_manager.delete_course(course_id)
            if success:
                self.color_print(f"Course {course.get_name()} deleted successfully!", "green")
            else:
                self.color_print("Course deletion failed", "red")
        else:
            self.color_print("Deletion cancelled", "yellow")

    def display_table(self, headers: list, rows: list, max_col_width: int = 20) -> None:
        """
        Display table data

        Parameters:
            headers (list): Header list
            rows (list): Row data list, each element is a list
            max_col_width (int): Maximum column width, default is 20
        """
        if not headers or not rows:
            print("No data to display")
            return

        # Get terminal width
        try:
            import os
            terminal_width = os.get_terminal_size().columns
        except:
            # If terminal width cannot be obtained, use default value
            terminal_width = 80

        # Calculate maximum width for each column, considering Chinese characters
        col_widths = []
        for i, header in enumerate(headers):
            # Calculate header width (Chinese characters count as 2 characters)
            header_width = sum(2 if ord(c) > 127 else 1 for c in str(header))
            col_widths.append(header_width)
        
        for row in rows:
            for i, cell in enumerate(row):
                if i < len(col_widths):
                    # Calculate cell width (Chinese characters count as 2 characters)
                    cell_width = sum(2 if ord(c) > 127 else 1 for c in str(cell))
                    col_widths[i] = max(col_widths[i], cell_width)
        
        # Limit maximum column width
        col_widths = [min(width, max_col_width) for width in col_widths]
        
        # Calculate total table width (including borders and separators)
        total_width = sum(col_widths) + len(col_widths) + 1  # +1 for the last border
        
        # If table is too wide, shrink column widths proportionally
        if total_width > terminal_width:
            # Calculate total width to be reduced
            excess_width = total_width - terminal_width
            
            # Shrink each column width proportionally, but keep minimum width
            min_col_width = 5  # Minimum column width
            total_current_width = sum(col_widths)
            
            # Try proportional reduction first
            for i in range(len(col_widths)):
                if col_widths[i] > min_col_width:
                    reduction = int(col_widths[i] * excess_width / total_current_width)
                    col_widths[i] = max(min_col_width, col_widths[i] - reduction)
            
            # If still too wide, force reduction
            total_width = sum(col_widths) + len(col_widths) + 1
            if total_width > terminal_width:
                excess_width = total_width - terminal_width
                for i in range(len(col_widths)):
                    if col_widths[i] > min_col_width:
                        col_widths[i] = max(min_col_width, col_widths[i] - 1)
                        excess_width -= 1
                        if excess_width <= 0:
                            break
        
        # Add some padding
        col_widths = [width + 2 for width in col_widths]

        # Draw header
        header_line = "|"
        separator_line = "|"
        for i, header in enumerate(headers):
            # Truncate overly long headers
            header_text = str(header)
            display_width = sum(2 if ord(c) > 127 else 1 for c in header_text)
            if display_width > col_widths[i] - 2:
                # Truncate and add ellipsis
                truncated = ""
                current_width = 0
                for c in header_text:
                    char_width = 2 if ord(c) > 127 else 1
                    if current_width + char_width > col_widths[i] - 4:  # Leave space for ellipsis
                        truncated += "..."
                        break
                    truncated += c
                    current_width += char_width
                header_text = truncated
            
            header_line += f" {header_text:<{col_widths[i]-2}} |"
            separator_line += "-" * col_widths[i] + "|"

        print(separator_line)
        print(header_line)
        print(separator_line)

        # Draw data rows
        for row in rows:
            row_line = "|"
            for i, cell in enumerate(row):
                if i < len(col_widths):
                    # Truncate overly long cell content
                    cell_text = str(cell)
                    display_width = sum(2 if ord(c) > 127 else 1 for c in cell_text)
                    if display_width > col_widths[i] - 2:
                        # Truncate and add ellipsis
                        truncated = ""
                        current_width = 0
                        for c in cell_text:
                            char_width = 2 if ord(c) > 127 else 1
                            if current_width + char_width > col_widths[i] - 4:  # Leave space for ellipsis
                                truncated += "..."
                                break
                            truncated += c
                            current_width += char_width
                        cell_text = truncated
                    
                    row_line += f" {cell_text:<{col_widths[i]-2}} |"
            print(row_line)

        print(separator_line)

    def clear_screen(self) -> None:
        """
        Clear screen
        """
        import os
        os.system('cls' if os.name == 'nt' else 'clear')


def main():
    """Main function, start CLI interface"""
    system = LMSSystem()
    
    # Initialize system
    if not system.initialize():
        print("Error: System initialization failed")
        return
    
    cli = CLI(system)
    cli.start()


if __name__ == "__main__":
    main()